package com.playcrab.adouban;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
 
import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.douban.UserEntry;
import com.google.gdata.util.ServiceException;
import com.playcrab.adouban.util.Constants;
import com.playcrab.adouban.util.DoubanAPI;

/**
 * @author kevinye
 */
public class AuthSuccess extends BaseActivity {
	private static final String LOG_TAG = "AuthSuccess";
	 
	SharedPreferences settings;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		saveAccessToken();
		saveUserInfo();
		Intent intent = new Intent(AuthSuccess.this,
				Main.class);
		startActivity(intent);
	}
	
	private String saveAccessToken() {

		DoubanService myService = DoubanAPI.getInstance().getService();
		String url = myService.getAuthorizationUrl(Constants.OAUTH_CALLBACK);

		 settings = getSharedPreferences(
				 Constants.PREF_DOUBAN, 0);
		
		String requestToken = settings.getString(Constants.OAUH_TOKEN,
				"false");
		String requestTokenSecret = settings.getString(Constants.OAUTH_TOKEN_SECRET,
		"false");
		Log.i(LOG_TAG, "requestToken=" + requestToken);
		myService.setRequestToken(requestToken);
		myService.setRequestTokenSecret(requestTokenSecret);
		
		ArrayList<String> list = myService.getAccessToken();
		String acessToken = list.get(0);
		String acessTokenSecret = list.get(1);
		Log.i(LOG_TAG, "acessToken=" + acessToken);
		Log.i(LOG_TAG, "acessTokenSecret=" + acessTokenSecret);
		settings.edit().putString(Constants.ACCESS_TOKEN, acessToken)
				.putString(Constants.ACCESS_TOKEN_SECRET, acessTokenSecret)
				.commit();

		return url;
	}
	/*
	 * 保存用户的信息，目前只先保存用户名
	 */
	private void saveUserInfo(){
		Log.i(LOG_TAG,"saveUserInfo");
		try {
			DoubanService service = getAuthedDoubanService();
			UserEntry userEntry=	service.getAuthorizedUser();
			settings.edit().putString(Constants.USER_NAME, userEntry.getUid()).commit();
			Log.i(LOG_TAG,"saveUserInfo"+userEntry.getUid());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}